import Vue from 'vue';
import axios from 'axios';
import rem from '@/utils/rem';
import App from '@/app';
import '@/style/dist/app.css';
import noticeHub from '@/components/notice-hub';
import router from '@/utils/router';
import { Button, Upload, Input, Select, Option } from 'element-ui';

Vue.use(Upload);
Vue.use(Input);
Vue.use(Button);
Vue.use(Select);
Vue.use(Option);

Vue.config.productionTip = false;

Vue.directive('focus', {
  inserted(el, state) {
    if (state.value) {
      el.focus();
    }
  },
});

// register as directive
axios.defaults.withCredentials = true;
Vue.prototype.$http = axios;

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'http://127.0.0.1:8050';
} else {
  axios.defaults.baseURL = 'https://www.todaytomato.com:8050';
}

Vue.prototype.$noticeHub = noticeHub;

const eventHub = new Vue();
Vue.prototype.$eventHub = eventHub;

const stateHub = {
  auth: false,
  csrf: '',
  username: '',
  rolename: '',
};
Vue.prototype.$stateHub = stateHub;

router.beforeEach((to, from, next) => {
  const cache = to.path;
  if (stateHub.auth || to.path === '/account/security/login' || to.path === '/account/security/signup' || from.path === '/account/security/logout') {
    next();
  } else {
    axios.request({
      url: 'api/verify',
      method: 'get',
    }).then((response) => {
      stateHub.auth = true;
      stateHub.username = response.data.username;
      stateHub.role = response.data.role;
      next(cache);
    }).catch(() => {
      stateHub.auth = false;
      next('/account/security/login');
    });
  }
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: {
    App,
  },
  mounted() {
    window.addEventListener('resize', () => {
      rem.run();
      this.$eventHub.$emit('resize');
    }, false);
    window.addEventListener('pageshow', () => {
      rem.run();
    }, false);
    rem.run();
  },
  template: '<app></app>',
  router,
});

